//
//  JCReportProposalVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/30.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCReportProposalVC.h"
#import "JCProgressView.h"
#import "JCClubApi.h"
#import "JCReportProModel.h"
#import "JCReportModel.h"
@import Charts;

@interface JCReportProposalVC ()<ChartViewDelegate>
@property (weak, nonatomic) IBOutlet PieChartView *pieView;
@property (weak, nonatomic) IBOutlet JCProgressView *foreHandView;
@property (weak, nonatomic) IBOutlet JCProgressView *backHandView;

@property (weak, nonatomic) IBOutlet LineChartView *sweetView;
@property (weak, nonatomic) IBOutlet UILabel *sweetValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *sweetGradeLabel;

@property (weak, nonatomic) IBOutlet BarChartView *speedView;
@property (weak, nonatomic) IBOutlet UILabel *speedValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *speedGradeLabel;

@property (weak, nonatomic) IBOutlet BarChartView *powerView;
@property (weak, nonatomic) IBOutlet UILabel *powerValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *powerGradeLabel;

@property (strong, nonatomic) JCReportProModel *reportModel;

@end

@implementation JCReportProposalVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)loadData{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getReportProForUserID:_userID
                              clubID:_clubID
                                year:_reportListModel.year
                            yearWeek:_reportListModel.yearWeek
                            complete:^(NSError *error, JCReportProModel *reportProModel) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            weakSelf.reportModel = reportProModel;
            [weakSelf refreshData];
        }
    }];
}

- (void)refreshData{
    
    [self setPieChartViewData:@[_reportModel.foreHand,_reportModel.backHand]
                        color:@[UIColorFromHex(0x68659b),UIColorFromHex(0x48b17f)]
                 pieChartView:_pieView];
    
    NSMutableArray *speeds = [NSMutableArray array];
    NSMutableArray *powers = [NSMutableArray array];
    NSMutableArray *sweets = [NSMutableArray array];
    
    for (JCReportProSubData *data in _reportModel.weekData) {
        [speeds addObject:data.avgSpeed];
        [powers addObject:data.avgStrength];
        [sweets addObject:data.sweetRate];
    }
    
//    [YFUserDefaults generalMetricSystemUnit];
//    [Common kmhToMph:round(speed)]
    
    NSString *unit;
    if (![YFUserDefaults generalMetricSystemUnit]) {
        unit = @"mph";
    }else{
        unit = @"kph";
    }
    [self setBarChartViewData:speeds.mutableCopy forView:_speedView color:UIColorFromHex(0xfe4ee1)];
    _speedValueLabel.text = [_reportModel.gradeReference.avgSpeed stringByAppendingString:unit];
    _speedGradeLabel.text = _reportModel.grade.avgSpeed;
    [self setBarChartViewData:powers.mutableCopy forView:_powerView color:UIColorFromHex(0xff605e)];
    _powerValueLabel.text = [_reportModel.gradeReference.avgStrength stringByAppendingString:@"N"];
    _powerGradeLabel.text = _reportModel.grade.avgStrength;
    [self setLineChartViewData:sweets forView:_sweetView color:UIColorFromHex(0xff8400)];
    _sweetValueLabel.text = [_reportModel.gradeReference.sweetRate stringByAppendingString:@"%"];
    _sweetGradeLabel.text = _reportModel.grade.sweetRate;
    
    _foreHandView.progressColor = UIColorFromHex(0x68659b);
    _foreHandView.trackColor = [UIColorFromHex(0x999999) colorWithAlphaComponent:0.5];
    _foreHandView.progressWidth = 5;
    _backHandView.progressColor = UIColorFromHex(0x48b17f);
    _backHandView.trackColor = [UIColorFromHex(0x999999) colorWithAlphaComponent:0.5];
    _backHandView.progressWidth = 5;
    [_foreHandView setProgress:_reportModel.foreHandPer.floatValue animated:YES];
    [_backHandView setProgress:_reportModel.backHandPer.floatValue animated:YES];
    
//    [_sweetView highlightValueWithX:1 y:_reportModel.gradeReference.sweetRate.floatValue dataSetIndex:0 callDelegate:YES];
//    [_speedView highlightValueWithX:1 y:_reportModel.gradeReference.avgSpeed.floatValue dataSetIndex:1 callDelegate:YES];
//    [_powerView highlightValueWithX:1 y:_reportModel.gradeReference.avgStrength.floatValue dataSetIndex:2 callDelegate:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)initCode{
    [self setupPieChartView:_pieView];
    [self setupBarChartView:_speedView];
    [self setupBarChartView:_powerView];
    [self setupLineChartView:_sweetView];
}

#pragma mark - 设置PieChartView
- (void)setupPieChartView:(PieChartView *)chartView{
    chartView.usePercentValuesEnabled = NO;
    chartView.drawSlicesUnderHoleEnabled = NO;
    chartView.chartDescription.enabled = NO;
    chartView.drawHoleEnabled = NO;
    [chartView setExtraOffsetsWithLeft:0 top:0 right:0 bottom:0];
    chartView.legend.enabled = NO;
    chartView.drawCenterTextEnabled = NO;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;
}

- (void)setPieChartViewData:(NSArray <NSString *> *)valueStrings
                      color:(NSArray <UIColor *> *)colors
               pieChartView:(PieChartView *)pieChartView{
    NSMutableArray *values = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < valueStrings.count; i++){
        [values addObject:[[PieChartDataEntry alloc] initWithValue:valueStrings[i].integerValue]];
    }
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:values];
    
    dataSet.drawIconsEnabled = NO;
    dataSet.selectionShift = 5;
    dataSet.sliceSpace = 2.0;
    
    dataSet.colors = colors;
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterNoStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:kOpenSansFont(OpenSansSemibold, 16)];
    [data setValueTextColor:UIColor.whiteColor];
    
    pieChartView.data = nil;
    pieChartView.data = data;
    [pieChartView highlightValues:nil];
}

#pragma mark - 设置BarChartView
- (void)setupBarChartView:(BarLineChartViewBase *)chartView{
    chartView.chartDescription.enabled = NO;
//    chartView.drawGridBackgroundEnabled = NO;
    chartView.legend.enabled = NO;
    
    chartView.rightAxis.enabled = NO;
    chartView.leftAxis.enabled = YES;
    chartView.leftAxis.axisMaximum = chartView == _speedView?(kMaxSpeed):(kMaxPower);
    chartView.leftAxis.axisMinimum = 0;
    chartView.leftAxis.drawZeroLineEnabled = YES;
    chartView.leftAxis.zeroLineColor = [UIColor whiteColor];
    chartView.leftAxis.drawGridLinesEnabled = NO;
    chartView.leftAxis.drawLabelsEnabled = NO;
    chartView.leftAxis.labelTextColor = UIColorFromHex(0x999999);
    chartView.leftAxis.drawAxisLineEnabled = NO;
    chartView.leftAxis.zeroLineWidth = 0.5;
    chartView.leftAxis.zeroLineColor = UIColorFromHex(0x999999);
//
    chartView.xAxis.labelPosition = XAxisLabelPositionBottom;
    chartView.xAxis.drawGridLinesEnabled = NO;
    chartView.xAxis.labelTextColor = UIColorFromHex(0x999999);
    chartView.xAxis.axisLineColor = UIColorFromHex(0x999999);
    chartView.xAxis.labelFont = kOpenSansFont(OpenSansBold, 10);
}

- (void)setBarChartViewData:(NSArray <NSString *> *)values
                    forView:(BarChartView *)barChartView
                      color:(UIColor *)color{
    
    NSArray *xValues = @[@"M.",@"T.",@"W.",@"T.",@"F.",@"S.",@"S."];

    NSMutableArray *yVals = [NSMutableArray array];
    for (int i = 0; i < 7; i++) {
        double value = [values[i] doubleValue];
        [yVals addObject:[[BarChartDataEntry alloc] initWithX:i y:value]];
    }
    
    BarChartDataSet *set1 = nil;
    set1 = [[BarChartDataSet alloc] initWithValues:yVals label:@""];
    set1.highlightEnabled = NO;
    set1.drawValuesEnabled = NO;
    [set1 setColors:@[color]];
    
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];
    
    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    [data setValueFont:[UIFont systemFontOfSize:10]];
    data.barWidth = 0.3f;
    
    ChartLimitLine *limitLine;
    if (barChartView == _speedView) {
        limitLine = [[ChartLimitLine alloc] initWithLimit:_reportModel.gradeReference.avgSpeed.floatValue
                                                    label:_reportModel.gradeReference.avgSpeed];
    }else if (barChartView == _powerView){
        limitLine = [[ChartLimitLine alloc] initWithLimit:_reportModel.gradeReference.avgStrength.floatValue
                                                    label:_reportModel.gradeReference.avgStrength];
    }
    limitLine.lineWidth = 0.5;
    limitLine.lineColor = UIColorFromHex(0x999999);
    limitLine.lineDashLengths = @[@1.0f, @3.0f];
    limitLine.labelPosition = ChartLimitLabelPositionRightTop;
    limitLine.valueTextColor = UIColorFromHex(0x999999);
    limitLine.valueFont = [UIFont systemFontOfSize:10];
    [barChartView.leftAxis addLimitLine:limitLine];
    barChartView.leftAxis.drawLimitLinesBehindDataEnabled = YES;
    
    if (xValues.count > 0) {
        barChartView.xAxis.axisMaxValue = xValues.count - 1 + 0.8;
        barChartView.xAxis.labelCount = xValues.count;
        barChartView.xAxis.valueFormatter = [[KBValueFormatter alloc] initWithDateArr:xValues];
    }
    barChartView.data = data;
}

#pragma mark - 设置LineChartView
- (void)setupLineChartView:(LineChartView *)chartView{

    chartView.descriptionText = @"";
    chartView.noDataText = @"";
    chartView.legend.enabled = NO;
    chartView.delegate = self;
    
    chartView.scaleYEnabled = NO;
    chartView.scaleXEnabled = NO;
    chartView.scaleEnabled = NO;
    chartView.doubleTapToZoomEnabled = NO;
    chartView.dragDecelerationEnabled = NO;
    chartView.dragDecelerationFrictionCoef = 0;
    
    chartView.xAxis.labelPosition = XAxisLabelPositionBottom;
    chartView.xAxis.drawGridLinesEnabled = NO;
    chartView.xAxis.labelTextColor = UIColorFromHex(0x999999);
    chartView.xAxis.axisLineColor = UIColorFromHex(0x999999);
    chartView.xAxis.labelFont = kOpenSansFont(OpenSansBold, 10);
    chartView.xAxis.drawAxisLineEnabled = NO;
    
    chartView.leftAxis.enabled = YES;
    chartView.leftAxis.axisMaximum = 100;
    chartView.leftAxis.axisMinimum = 0;
    chartView.leftAxis.drawZeroLineEnabled = YES;
    chartView.leftAxis.zeroLineColor = [UIColor whiteColor];
    chartView.leftAxis.drawGridLinesEnabled = NO;
    chartView.leftAxis.drawLabelsEnabled = NO;
    chartView.leftAxis.labelTextColor = UIColorFromHex(0x999999);
    chartView.leftAxis.drawAxisLineEnabled = NO;
    chartView.leftAxis.zeroLineWidth = 0.5;
    chartView.leftAxis.zeroLineColor = UIColorFromHex(0x999999);
    
    chartView.rightAxis.enabled = NO;
}

- (void)setLineChartViewData:(NSArray <NSString *> *)values
                     forView:(LineChartView *)lineChartView
                       color:(UIColor *)color{
    
    NSMutableArray *arr = [NSMutableArray array];
    NSArray *xValues = @[@"M.",@"T.",@"W.",@"T.",@"F.",@"S.",@"S."];
    CGFloat maxValue = 0;
    for (NSInteger i = 0; i < values.count; i++) {
        CGFloat value = [values[i] floatValue];
        maxValue = maxValue > value ? maxValue : value;
        if (lineChartView == _sweetView) {
            value = value * 100;
        }
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:value];
        [arr addObject:entry];
    }
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:arr label:nil];
    set.lineWidth = 2;
    set.drawValuesEnabled = NO;
    set.drawCirclesEnabled = NO;
    set.circleRadius = 5.0f;
    set.circleColors = @[color];
    set.drawCircleHoleEnabled = YES;
    set.circleHoleRadius = 3.0f;
    set.circleHoleColor = [UIColor whiteColor];
    set.mode = LineChartModeLinear;
    set.drawFilledEnabled = YES;
    [set setColor:color];
    NSArray *gradientColors = @[(id)[UIColor clearColor].CGColor,
                                (id)color.CGColor];
    CGGradientRef gradientRef = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
    set.fillAlpha = 0.9f;
    set.fill = [ChartFill fillWithLinearGradient:gradientRef angle:90.0f];
    CGGradientRelease(gradientRef);
    
//    set.drawVerticalHighlightIndicatorEnabled = NO;
//    set.highlightLineDashLengths = @[@3,@1];
//    set.highlightColor = UIColorFromHex(0x999999);
    
    ChartLimitLine *limitLine = [[ChartLimitLine alloc] initWithLimit:_reportModel.gradeReference.sweetRate.floatValue label:[_reportModel.gradeReference.sweetRate stringByAppendingString:@"%"]];;
    limitLine.lineWidth = 0.5;
    limitLine.lineColor = UIColorFromHex(0x999999);
    limitLine.lineDashLengths = @[@1.0f, @3.0f];
    limitLine.labelPosition = ChartLimitLabelPositionRightTop;
    limitLine.valueTextColor = UIColorFromHex(0x999999);
    limitLine.valueFont = [UIFont systemFontOfSize:10];
    [lineChartView.leftAxis addLimitLine:limitLine];
    lineChartView.leftAxis.drawLimitLinesBehindDataEnabled = YES;
    
    if (xValues.count > 0) {
        lineChartView.xAxis.axisMaxValue = xValues.count - 1 + 0.8;
        lineChartView.xAxis.labelCount = xValues.count;
        lineChartView.xAxis.valueFormatter = [[KBValueFormatter alloc] initWithDateArr:xValues];
    }
    
    lineChartView.data = nil;
    lineChartView.data = [[LineChartData alloc] initWithDataSet:set];
    [lineChartView animateWithYAxisDuration:1.0f easingOption:ChartEasingOptionEaseInOutQuad];
    
}

- (void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight{
    if (highlight.dataSetIndex == 0) {
        CGPoint center = [_sweetView pixelForValuesWithX:entry.x
                                                       y:entry.y
                                                    axis:AxisDependencyLeft];
    }else if (highlight.dataSetIndex == 1){
        CGPoint center = [_speedView pixelForValuesWithX:entry.x
                                                       y:entry.y
                                                    axis:AxisDependencyLeft];
    }else if (highlight.dataSetIndex == 2){
        CGPoint center = [_powerView pixelForValuesWithX:entry.x
                                                       y:entry.y
                                                    axis:AxisDependencyLeft];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end







@implementation KBValueFormatter{
    NSArray *_dateArr;
}

- (id)initWithDateArr:(NSArray *)arr {
    if (self = [super init]) {
        _dateArr = [NSArray arrayWithArray:arr];
    }
    return self;
}

- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis {
    return _dateArr[(int)value];
}

@end  
